<?php

use App\Models\Post;
use App\Models\Tag;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PostsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // 拉取所有标签
        $tags = Tag::all()->pluck('tag')->all();

        // 清理表数据
        Post::truncate();

        // 清除中间表的数据
        DB::table('post_tag_pivot')->truncate();

        // 填充20篇文章
        factory(Post::class, 20)->create()->each(function ($post) use ($tags) {
            // %30文章没有标签
            if (mt_rand(1, 100) <= 30) {
                return;
            }

            // 打乱标签数组
            shuffle($tags);
            $postTags = [$tags[0]];

            // 30%文章有两个标签
            if (mt_rand(1, 100) <= 30) {
                $postTags[] = $tags[1];
            }

            $post->syncTags($postTags);
        });
    }
}
